//
//  RBSecondKillConfirmOrderVC.m
//  zhongzhenglu
//
//  Created by 马军凯 on 2023/3/25.
//

#import "RBSecondKillConfirmOrderVC.h"
#import "RBSecondKillConfirmOrderResponse.h" //model
#import "RBTextView.h"
#import "RBAddresssListVC.h" //选择地址
#import "RBInvoiceHeaderManageVC.h" //开票
#import "RBCashierVC.h" //收银台
#import "RBConfirmOrderResponse.h"

@interface RBSecondKillConfirmOrderVC ()
//地址
@property (nonatomic, strong) IBOutlet UIView *addressView;
@property (nonatomic, strong) IBOutlet UILabel *addressNameL;
@property (nonatomic, strong) IBOutlet UILabel *addressL;
//自提
@property (nonatomic, strong) IBOutlet UIView *ziti_addressView;
@property (nonatomic, strong) IBOutlet UILabel *ziti_addressL;
//留言
@property (nonatomic, strong) IBOutlet UIView *noteView;
@property (nonatomic, strong) IBOutlet UITextView *noteTextView;

//scrollView
@property (nonatomic, strong) UIScrollView *scrollView;
//底部view
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UILabel *priceL; //价格

@property (nonatomic, strong) UILabel *invoiceL;

/** 0 快递 1自取 */
@property (nonatomic, assign) NSInteger addressTypeIndex;

@property (nonatomic, strong) RBSecondKillConfirmOrderResponse *response;

//地址model
@property (nonatomic, strong) RBAddressListModel *addressModel;
@property (nonatomic, strong) RBGroupStartZitiModel *zitiModel;
//发票
@property (nonatomic, strong) RBInvoiceHeaderManageModel *invoiceModel;

@end

@implementation RBSecondKillConfirmOrderVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
    [self getData];
}

#pragma mark - Private
- (void)setup {
    self.title = @"确认订单";
    self.view.backgroundColor = [RBThemeConfig bgGrayColor];
    self.addressNameL.numberOfLines = 0;
    self.addressL.numberOfLines = 0;
    [self.addressView rbAddTapGesWithTarget:self action:@selector(addressViewTapped)];
    [self.ziti_addressView rbAddTapGesWithTarget:self action:@selector(zitiAddressViewTapped)];
    self.bottomView.hidden = YES;
    [self.noteView zoomSubViewsWithSelf];
    self.noteView.height = Zoom(self.noteView.height);
}

- (void)fillData {
    //model
    RBSecondKillConfirmOrderModel *allModel = self.response.data;
    //地址model
    if (allModel.address && allModel.address.count > 0) {
        self.addressModel = allModel.address.firstObject;
    }
    //刷新地址
    [self reloadAddressDisplay];
    //刷新价格
    [self reloadPrice];
    //底部显示
    self.bottomView.hidden = NO;
    //页面数据
    [self.scrollView rbSetContentWidth:kRBMainScreenWidth];
    //地址
    [self.scrollView addView:({
        UIView *view = UIView.new;
        view.backgroundColor = UIColor.whiteColor;
        [view rbSetCornerRadius:Zoom(10)];
        [view view_addView:({
            UIView *view = UIView.new;
            [view h_view_addView:[self addressTypeViewWithTitle:@"快递邮寄" tag:0] withHeight:CGFLOAT_MIN width:Zoom(175) top:0 bottom:0 left:0 right:CGFLOAT_MIN centerY:NO];
            [view h_view_addView:[self addressTypeViewWithTitle:@"门店自提" tag:1] withHeight:CGFLOAT_MIN width:Zoom(175) top:0 bottom:0 left:0 right:CGFLOAT_MIN centerY:NO];
            view;
        }) withHeight:Zoom(50) width:CGFLOAT_MIN top:0 bottom:0 left:0 right:0 centerX:0];
        [view view_addView:({
            UIView *view = UIView.new;
            view.backgroundColor = [RBThemeConfig lineGrayColor];
            view;
        }) withHeight:1 width:Zoom(326) top:0 bottom:0 left:0 right:0 centerX:1];
        if (self.addressTypeIndex == 0) {
            [view view_addView:self.addressView withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:Zoom(10) bottom:0 left:0 right:0 centerX:0];
        } else {
            [view view_addView:self.ziti_addressView withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:0 bottom:0 left:0 right:0 centerX:0];
        }
        view;
    }) withHeight:CGFLOAT_MIN width:Zoom(350) top:Zoom(10) bottom:0 left:CGFLOAT_MIN right:CGFLOAT_MIN centerX:YES];
    //店铺+商品
    [self.scrollView addView:({
        UIView *view = UIView.new;
        view.backgroundColor = UIColor.whiteColor;
        [view rbSetCornerRadius:Zoom(8)];
        //店铺
        [view view_addView:[self shopViewWithData:allModel] withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:0 bottom:0 left:0 right:0 centerX:0];
        //商品
        [view view_addView:[self goodsViewWithData:allModel] withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:Zoom(16) bottom:Zoom(22) left:0 right:0 centerX:0];
        
        view;
    }) withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:Zoom(10) bottom:Zoom(22) left:Zoom(15) right:Zoom(15) centerX:0];
    //商品金额
    [self.scrollView addView:({
        UIView *view = UIView.new;
        view.backgroundColor = UIColor.whiteColor;
        [view rbSetCornerRadius:Zoom(8)];
        
        [view view_addView:({
            UIView *view = [self itemWithTitle:@"商品小计" des:[NSString stringWithFormat:@"¥%@", allModel.current_price] needArrow:NO];
            view;
        }) withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:Zoom(24) bottom:Zoom(24) left:0 right:0 centerX:0];
        
        [view view_addView:({
            UIView *view = [self itemWithTitle:@"运费" des:@"+¥0.00" needArrow:NO];
            view;
        }) withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:Zoom(24) bottom:Zoom(24) left:0 right:0 centerX:0];
        [view view_addView:({
            UIView *view = [self itemWithTitle:@"发票" des:@"无需发票" needArrow:YES];
            UILabel *invoiceL = [view viewWithTag:333];
            self.invoiceL = invoiceL;
            [view rbAddTapGesWithTarget:self action:@selector(chooseInvoiceTapped)];
            view;
        }) withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:Zoom(24) bottom:Zoom(24) left:0 right:0 centerX:0];
        view;
    }) withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:Zoom(10) bottom:Zoom(10) left:Zoom(15) right:Zoom(15) centerX:NO];
    //备注
    [self.scrollView addView:self.noteView withHeight:self.noteView.height width:Zoom(350) top:Zoom(10) bottom:Zoom(10) left:CGFLOAT_MIN right:CGFLOAT_MIN centerX:YES];
    //计算价格
    [self reloadPrice];
}

//刷新地址
- (void)reloadAddressDisplay {
    if (self.addressModel) {
        self.addressNameL.attributedText = [RanTool attributeStringMaker:^(NSMutableArray *maker) {
            [maker addAttributeStringWithFont:[UIFont systemFontOfSize:Zoom(15)] color:[RBThemeConfig textBlackColor] string:[NSString stringWithFormat:@"收货人：%@", self.addressModel.name] lineSpacing:Zoom(4)];
            [maker addAttributeStringWithFont:[UIFont systemFontOfSize:Zoom(15)] color:[RBThemeConfig textBlackColor] string:@"　" lineSpacing:Zoom(4)];
            [maker addAttributeStringWithFont:[UIFont systemFontOfSize:Zoom(13)] color:[UIColor colorWithHexString:@"#969593"] string:self.addressModel.mobile lineSpacing:Zoom(4)];
        }];
        self.addressL.attributedText = [RanTool attributeStringMaker:^(NSMutableArray *maker) {
            [maker addAttributeStringWithFont:[UIFont systemFontOfSize:Zoom(14)] color:[UIColor colorWithHexString:@"#4D4948"] string:[NSString stringWithFormat:@"%@ %@ %@ %@", self.addressModel.province, self.addressModel.city, self.addressModel.area, self.addressModel.address] lineSpacing:Zoom(4)];
        }];
    } else {
        self.addressNameL.attributedText = [RanTool attributeStringMaker:^(NSMutableArray *maker) {
            [maker addAttributeStringWithFont:[UIFont systemFontOfSize:Zoom(15)] color:[RBThemeConfig textBlackColor] string:@"收货地址" lineSpacing:Zoom(4)];
            }];
        self.addressL.attributedText = [RanTool attributeStringMaker:^(NSMutableArray *maker) {
            [maker addAttributeStringWithFont:[UIFont systemFontOfSize:Zoom(14)] color:[UIColor colorWithHexString:@"#4D4948"] string:@"请选择" lineSpacing:Zoom(4)];
        }];
    }
    if (self.zitiModel) {
        NSMutableString *stringM = NSMutableString.string;
        [stringM appendFormat:@"门店:%@",self.zitiModel.title];
        [stringM appendFormat:@"\n地址:%@ %@ %@ %@",kRBNotNilString(self.zitiModel.add_pro),kRBNotNilString(self.zitiModel.add_city),kRBNotNilString(self.zitiModel.add_area), kRBNotNilString(self.zitiModel.address)];
        [stringM appendFormat:@"\n营业时间:%@ %@",kRBNotNilString(self.zitiModel.yingye_week),kRBNotNilString(self.zitiModel.yingye_time)];
        self.ziti_addressL.attributedText = [RanTool attributeStringMaker:^(NSMutableArray *maker) {
            [maker addAttributeStringWithFont:[UIFont systemFontOfSize:Zoom(13)] color:[UIColor colorWithHexString:@"#4D4948"] string:stringM lineSpacing:Zoom(7)];
        }];;
    } else {
        self.ziti_addressL.text = @"请选择自提点";
    }
}
//计算价格
- (CGFloat)calculationPrice {
    RBSecondKillConfirmOrderModel *model = self.response.data;
    CGFloat total_price = [model.current_price floatValue];
    
    return total_price;
}
//刷新价格
- (void)reloadPrice {
    NSString *priceString = [NSString stringWithFormat:@"%.2f", [self calculationPrice]];
    
    self.priceL.attributedText = [RanTool attributeStringMaker:^(NSMutableArray *maker) {
        [maker addAttributeStringWithFont:[UIFont systemFontOfSize:Zoom(13)] color:[RBThemeConfig textBlackColor] string:@"合计"];
        [maker addAttributeStringWithFont:[UIFont boldSystemFontOfSize:Zoom(16)] color:[RBThemeConfig priceRedColor] string:@"¥"];
        [maker addAttributeStringWithFont:[UIFont boldSystemFontOfSize:Zoom(21)] color:[RBThemeConfig priceRedColor] string:priceString];
//        [maker addAttributeStringWithFont:[UIFont boldSystemFontOfSize:Zoom(14)] color:[RBThemeConfig priceRedColor] string:@".00"];
    }];
}

#pragma mark - Network

- (void)getData {
    __weak typeof(self) weak_self = self;
    [self viewLoadDataWithParam:^(NSMutableDictionary *dicM) {
        dicM[@"seckill_id"] = self.seckill_id;
        dicM[@""] = [RBAccountManager getUserId];
    } path:_Seckill_confirm_order post:YES log:YES responseClass:RBSecondKillConfirmOrderResponse.class desView:self.view showHud:YES showPlaceHolder:NO sucBlock:^(RBSecondKillConfirmOrderResponse *data) {
        weak_self.response = data;
        [weak_self fillData];
    } failBlock:^(RBSecondKillConfirmOrderResponse *data) {
        [weak_self.view showTip:data.message completion:nil];
    } reloadBlock:nil];
}

#pragma mark - Event
//选择配送方式
- (void)addressTypeItemViewTapped: (UITapGestureRecognizer *)ges {
    if(self.addressTypeIndex == ges.view.tag) return;
    self.addressTypeIndex = ges.view.tag;
    [self fillData];
}
//选择地址
- (void)addressViewTapped {
    __weak typeof(self) weak_self = self;
    RBAddresssListVC *vc = RBAddresssListVC.new;
    vc.selectBlock = ^(RBAddressListModel *model) {
        weak_self.addressModel = model;
        [weak_self reloadAddressDisplay];
    };
    [self.navigationController pushViewController:vc animated:YES];
}
//选择自提地址
- (void)zitiAddressViewTapped {
    RBSecondKillConfirmOrderModel *model = self.response.data;
    NSMutableArray *titleArray = NSMutableArray.array;
    for (RBGroupStartZitiModel *zitiModel in model.ziti_list) {
        [titleArray addObject:zitiModel.title];
    }
    LCWeakSelf;
    [JKAction showTitle:@"请选择自提点" message:nil btnArray:titleArray completion:^(int index) {
        weakSelf.zitiModel = model.ziti_list[index];
        [weakSelf reloadAddressDisplay];
    }];
}
//发票选择
- (void)chooseInvoiceTapped {
    LCWeakSelf;
    [JKAction showTitle:nil message:nil btnArray:@[@"无需发票", @"选择发票"] completion:^(int index) {
        if (index == 0) {
            weakSelf.invoiceL.text = @"无需发票";
            weakSelf.invoiceModel = nil;
        } else {
            RBInvoiceHeaderManageVC *vc = RBInvoiceHeaderManageVC.new;
            vc.block = ^(RBInvoiceHeaderManageModel * _Nonnull model) {
                weakSelf.invoiceModel = model;
                weakSelf.invoiceL.text = model.company_name;
            };
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
    }];
}
//提交订单
- (void)commitBtnTapped {
    if (self.addressTypeIndex == 0 && !self.addressModel) {
        [self.view showTip:@"请选择收件地址" completion:nil];
        return;
    }
    if (self.addressTypeIndex == 1 && !self.zitiModel) {
        [self.view showTip:@"请选择自提点" completion:nil];
        return;
    }
    //
    NSString *priceString = [NSString stringWithFormat:@"%.2f", [self calculationPrice]];
    LCWeakSelf;
    [self viewLoadDataWithParam:^(NSMutableDictionary *dicM) {
        dicM[@"seckill_id"] = self.seckill_id;
        dicM[@"user_id"] = [RBAccountManager getUserId];
        dicM[@"total_freight"] = @"0.00";
        dicM[@"num"] = @"1";
        dicM[@"total_price"] = priceString;
        dicM[@"mail_type"] = @(self.addressTypeIndex + 1);
        if (self.addressTypeIndex == 0) {
            dicM[@"user_address_id"] = self.addressModel.add_id;
        } else {
            dicM[@"zt_id"] = self.zitiModel.zt_id;
        }
        if (self.invoiceModel && self.invoiceModel.id.length > 0) {
            dicM[@"fapiao_list_id"] = self.invoiceModel.id;
        }
    } path:_Seckill_create_order post:YES log:YES responseClass:RBConfirmOrderSubmitResponse.class desView:self.view showHud:YES showPlaceHolder:NO sucBlock:^(RBConfirmOrderSubmitResponse *data) {
        if (data.succeed) {
            RBCashierVC *vc = RBCashierVC.new;
            vc.order_id = data.data.goods.order_id;
            vc.order_num = data.data.order_number;
            vc.order_price = data.data.total_price;
            [weakSelf.navigationController pushViewController:vc animated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                NSMutableArray *navigationArray = [NSMutableArray arrayWithArray:weakSelf.navigationController.viewControllers];
                [navigationArray removeObjectAtIndex:(navigationArray.count - 2)];
                weakSelf.navigationController.viewControllers = navigationArray;
            });
        }
    } failBlock:^(RBConfirmOrderSubmitResponse *data) {
        [weakSelf.view showTip:data.message completion:nil];
    } reloadBlock:nil];
}

#pragma mark - Getter
//scrollView
- (UIScrollView *)scrollView {
    if (!_scrollView) {
        self.scrollView = ({
            UIScrollView *view = UIScrollView.new;
            [self.view addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.top.mas_equalTo(0);
                make.bottom.mas_equalTo(self.bottomView.mas_top);
            }];
            view;
        });
    }
    return _scrollView;
}
//选择配送方式
- (UIView *)addressTypeViewWithTitle:(NSString *)title tag: (NSInteger)tag {
    UIView *view = UIView.new;
    view.tag = tag;
    [view rbAddTapGesWithTarget:self action:@selector(addressTypeItemViewTapped:)];
    [view view_addView:({
        UIView *view = UIView.new;
        [view h_view_addView:[RanTool imgViewWithMode:1 radius:0 imgName:self.addressTypeIndex == tag? @"addressListDefault": @"unsel"] withHeight:Zoom(15) width:Zoom(15) top:0 bottom:0 left:0 right:0 centerY:1];
        [view h_view_addView:[RanTool labelWithFontSize:Zoom(14) weight:0 color:[RBThemeConfig textBlackColor] align:0 text:title] withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:0 bottom:0 left:Zoom(10) right:0 centerY:0];
        view;
    }) withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:0 bottom:0 left:0 right:0 centerX:1];
    return view;
}
//店铺信息
- (UIView *)shopViewWithData:(RBSecondKillConfirmOrderModel *)data {
    UIView *view = UIView.new;
    
    [view h_view_addView:[RanTool labelWithFontSize:Zoom(16) weight:0 color:[RBThemeConfig textBlackColor] align:0 text:data.store_name] withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:Zoom(16) bottom:Zoom(16) left:Zoom(12) right:Zoom(12) centerY:NO];
    
    return view;
}
//商品信息
- (UIView *)goodsViewWithData:(RBSecondKillConfirmOrderModel *)data {
    UIView *view = UIView.new;
    
    [view view_addView:({
        UIView *view = UIView.new;
        [view h_view_addView:[RanTool imgViewWithMode:2 radius:Zoom(5) imgName:data.picurl] withHeight:Zoom(72) width:Zoom(82) top:0 bottom:CGFLOAT_MIN left:Zoom(12) right:CGFLOAT_MIN centerY:NO];
        [view h_view_addView:({
            UIView *view = UIView.new;
            [view view_addView:({
                UILabel *view = [RanTool labelWithFontSize:Zoom(16) weight:0 color:[RBThemeConfig textBlackColor] align:0 text:data.good_name];
                view.numberOfLines = 2;
                view;
            }) withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:0 bottom:0 left:0 right:0 centerX:0];
            
            [view view_addView:({
                UILabel *view = UILabel.new;
                view.attributedText = [RanTool attributeStringMaker:^(NSMutableArray *maker) {
                    [maker addAttributeStringWithFont:[UIFont boldSystemFontOfSize:Zoom(11)] color:[RBThemeConfig priceRedColor] string:@"¥"];
                    [maker addAttributeStringWithFont:[UIFont boldSystemFontOfSize:Zoom(15)] color:[RBThemeConfig priceRedColor] string:data.current_price];
                }];
                view;
            }) withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:Zoom(15) bottom:0 left:0 right:0 centerX:0];
            view;
        }) withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:0 bottom:0 left:Zoom(12) right:Zoom(8) centerY:NO];
        view;
    }) withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:0 bottom:0 left:0 right:0 centerX:NO];
    
    return view;
}
//左右
- (UIView *)itemWithTitle: (NSString *)title des: (NSString *)des needArrow: (BOOL)needArrow {
    UIView *view = UIView.new;
    
    UILabel *titleL = [RanTool labelWithFontSize:Zoom(13) weight:0 color:@"#333333" align:0 text:title];
    [view addSubview:titleL];
    [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(Zoom(16));
        make.top.bottom.mas_equalTo(0);
    }];
    [view h_view_addView:titleL withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:0 bottom:0 left:Zoom(16) right:0 centerY:0];
    
    UILabel *desL = [RanTool labelWithFontSize:Zoom(13) weight:0 color:@"#333333" align:0 text:des];
    desL.tag = 333;
    [desL addPriority:1];
    [view addSubview:desL];
    [view h_view_addView:desL withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:0 bottom:0 left:Zoom(12) right:Zoom(16) centerY:0];

    if (needArrow)
    {
        [view h_view_addView:[RanTool imgViewWithMode:1 radius:0 imgName:@"mine_arrow_right"] withHeight:Zoom(12) width:Zoom(7) top:CGFLOAT_MIN bottom:CGFLOAT_MIN left:Zoom(12) right:Zoom(16) centerY:YES];
    }
    
    return view;
}
//底部view
- (UIView *)bottomView {
    if (!_bottomView) {
        self.bottomView = ({
            UIView *view = UIView.new;
            [self.view addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.mas_equalTo(0);
                make.height.mas_equalTo(kRBSafeBottomHeight + Zoom(60));
            }];
            view.backgroundColor = UIColor.whiteColor;
            
            UIView *toolBar = UIView.new;
            [view addSubview:toolBar];
            [toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.top.mas_equalTo(0);
                make.height.mas_equalTo(Zoom(60));
            }];
            
            [toolBar h_view_addView:({
                UIView *priceV = UIView.new;
                
                [priceV h_view_addView:({
                    UILabel *view = [RanTool labelWithFontSize:Zoom(13) weight:0 color:@"#333333" align:0 text:@""];
                    self.priceL = view;
                    view;
                }) withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:0 bottom:0 left:0 right:0 centerY:0];
                priceV;
            }) withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:0 bottom:0 left:Zoom(13) right:Zoom(5) centerY:0];
            
            [toolBar h_view_addView:({
                RBGradientView *view = [RBGradientView gradientViewWithColors:@[[UIColor colorWithHexString:@"#518CFF"], [UIColor colorWithHexString:@"#2A6DF0"]] locations:nil vertical:NO];
                [view rbSetCornerRadius:Zoom(20)];
                [view rbAddTapGesWithTarget:self action:@selector(commitBtnTapped)];
                [view view_addView:[RanTool labelWithFontSize:Zoom(15) weight:0 color:UIColor.whiteColor align:1 text:@"提交订单"] withHeight:CGFLOAT_MIN width:CGFLOAT_MIN top:0 bottom:0 left:0 right:0 centerX:0];
                view;
            }) withHeight:Zoom(40) width:Zoom(106) top:CGFLOAT_MIN bottom:CGFLOAT_MIN left:0 right:Zoom(13) centerY:YES];
            
            view;
        });
    }
    return _bottomView;
}

@end
